package com.zd.lib.http.retrofit.utils;

import com.zd.lib.http.exception.ResponseException;
import com.zd.lib.http.response.BaseEntity;

import rx.Observable;
import rx.exceptions.Exceptions;
import rx.functions.Func1;

/**
 * Created by zoudong on 2017/2/4.
 * 检查 Response   code==0||Response==null
 */
public class ErrorCheckerTransformer<T extends BaseEntity<R>,R> implements Observable.Transformer<T,R> {
    @Override
    public Observable<R> call(Observable<T> tObservable) {
        return tObservable.map(new Func1<T, R>() {
            @Override
            public R call(T t) {
                BaseEntity entity =t;
                if (entity == null) {
                    entity= new BaseEntity(-999, "服务器返回空");
                }
                if (!entity.SUCCESS()) {
                    try {
                        throw new ResponseException(entity.getCode(),entity.getMsg());
                    } catch (ResponseException e) {
                        Exceptions.propagate(e);
                    }
                }
                return t.getData();
            }
        });
    }
}
